<template>
	<div class="trigger-configuration-edit" v-loading="loading">
		<div class="trigger-configuration-edit-rule trigger-step" v-if="selectFieldList.length">
			<div class="trigger-configuration-edit-rule-title">
				<div>选择需要编辑的数据</div>
				<div class="trigger-configuration-tip" v-if="isShowSelectTip">
					<i class="el-icon-question tip-icon"></i>
					<div class="tip-content">请至少设置一个条件</div>
				</div>
			</div>
			<div class="trigger-configuration-edit-rule-tip">过滤出需要编辑的数据。至少设置一个条件。(需将表单字段设置了"支持高级搜索"才可选择)</div>
			<div class="trigger-configuration-edit-rule-content">
				<conditionConfig 
					v-if="Object.keys(state.currentNodeInfoFront.options.fieldOptions || {}).length"
					:title="`查询的条件`" 
					v-model="state.currentNodeInfoFront.options.fieldOptions.select" 
					:filedList="selectFieldList"
					:fromFieldList="fromFieldList"
					@change="handleSelectChange"
					@selectChange="selectChange"
				></conditionConfig>
			</div>
		</div>
		<div class="trigger-configuration-edit-inform trigger-step">
			<div class="trigger-configuration-edit-inform-title">
				<div>选择需要修改的字段</div>
			</div>
			<div class="trigger-configuration-edit-inform-content">
				<newConfigItem
					v-for="(field, index) in updateFieldList"
					:key="field.enName"
					:field="{
						...field,
						required: false,
					}"
					:valueType="state.currentNodeInfoFront.options.fieldOptions.update[index].valueType"
					:value="state.currentNodeInfoFront.options.fieldOptions.update[index].value"
					:optionValue="state.currentNodeInfoFront.options.fieldOptions.update[index]"
					:index="index"
					:fromFieldList="fromFieldList"
					:toFieldList="updateFieldList"
					:isShowMasterData="true"
					@change="handleItemChange($event, index)"
      			/>
			</div>
		</div>
	</div>
</template>

<script>
import { getFieldMapping } from '@src/modules/trigger/api/trigger.js';
import state from '@src/modules/trigger/view/setting/util/state.js';
import conditionConfig from './conditionConfig.vue';
import actionMixin from '../mixins/actionMixin';
import newConfigItem from './newConfigItem.vue';

export default {
	name: "editConfig",
	components: {
		conditionConfig,
		newConfigItem,
	},
	mixins: [actionMixin],
	data() {
		return {
			selectFieldList: [],
			updateFieldList: [],
			fromFieldList: [],
			loading: false,
		};
	},
	computed: {
		state() {
			return state;
		},
		isShowSelectTip() {
			// 是否显示编辑的必填提示
			return !this.requiredCheck(state.currentNodeInfoFront.options?.fieldOptions?.select, 'select');
		},
	},
	created() {
		this.loading = true;
		getFieldMapping({
			fromApiIdList: (state.parentNodeApiIdList || []).filter(apiId => apiId !== null && apiId !== 'message' && apiId !== 'code'),
			toApiId: state.currentNodeInfoFront.options?.apiId,
		}).then(res => {
			// 需要用$set绑定响应式数据，否则会失去响应式，导致页面无法操作
			if (!state.currentNodeInfoFront.options?.fieldOptions?.update) {
				this.$set(state.currentNodeInfoFront.options, 'fieldOptions', {
					select: [
						{
							toEnName: '',
							operate: '',
							valueType: '',
							value: [],
						},
					],
					update: [
						{
							toEnName: '',
							operate: '',
							valueType: '',
							value: [],
						},
					],
				});
			}
			this.selectFieldList = this.changeChildrenData(res.data.selectFieldList);
			if (!this.selectFieldList.length) {
				this.$delete(state.currentNodeInfoFront.options.fieldOptions, 'select');
			}
			this.updateFieldList = this.changeChildrenData(res.data.toFieldList);
			this.fromFieldList = this.changeChildrenKey(this.changeChildrenData(res.data.fromFieldList));
			this.initUpdateFieldList();
		}).catch(err => {
			console.log(err)
		}).finally(() => {
			this.loading = false;
		});
	},
	methods: {
		// 选择其他字段的事件，我写这个是判断是固定值还是其他表单还是固定值 用这个判断是否改变
		selectChange(val, index) {
			if (val && val?.valueType == '3') {
                // 判断当前数据是否存在兼容性字段
                const existingIndex = this.state._compatibilityList.findIndex(item => item.index === index && item.nodeUniqueId === this.state.currentNodeInfoFront.uniqueId)
                // 如果不存在，则添加到兼容性列表中
                if (existingIndex === -1) {
                    this.state._compatibilityList.push({
                        '_isExecuteActionUpdateCondition': true,
                        'nodeUniqueId': this.state.currentNodeInfoFront.uniqueId,
						index: index,
                    })
                }
            }
		},
		handleSelectChange(val) {
			this.$set(state.currentNodeInfoFront.options.fieldOptions, 'select', val);
		},
		handleUpdateChange(val) {
			this.$set(state.currentNodeInfoFront.options.fieldOptions, 'update', val);
		},
		handleItemChange(value, index) {
			state.currentNodeInfoFront.options.fieldOptions.update[index].valueType = value.valueType;
            state.currentNodeInfoFront.options.fieldOptions.update[index].value = value.value;
			if (value._compatibilityField) {
				// 如果存在兼容性字段，则添加到兼容性列表中
				const existingIndex = state._compatibilityList.findIndex(item => item.i == index && item.nodeUniqueId === state.currentNodeInfoFront.uniqueId)
				// 如果不存在，则添加到兼容性列表中
				if (existingIndex === -1) {
					state._compatibilityList.push({
						...value._compatibilityField,
						nodeUniqueId: state.currentNodeInfoFront.uniqueId,
						index: index,
						status: 'update'
					})
				}
			}
		},
		initUpdateFieldList() {
			const insertList = state.currentNodeInfoFront.options?.fieldOptions?.update || [];

			// 创建一个新的空数组 newFields，结构从 toFieldList 中获取
			const newFields = this.updateFieldList.map(field => ({
				toEnName: field.enName,
				operate: null,
				// 默认选中对应字段
				valueType: field.valueTypeList.some(i => i.enName === '2') ? '2' : field.valueTypeList[0]?.enName,
				value: [],
			}));

			// 同步之前的数据到 newFields 中
			newFields.forEach(newField => {
				const existingField = insertList.find(field => field.toEnName === newField.toEnName);
				if (existingField) {
					newField.valueType = existingField.valueType;
					newField.value = existingField.value;
				}
			});
			// 更新 fieldOptions 的 insert 属性
			this.$set(state.currentNodeInfoFront.options, 'fieldOptions', {
				...state.currentNodeInfoFront.options.fieldOptions,
				update: newFields,
			});
		},
	}
};
</script>

<style scoped lang="scss">
.trigger-step {
	position: relative;
	padding-left: 20px;
}

.trigger-step::before {
	content: '';
	position: absolute;
	left: 0;
	top: 8px;
	width: 8px;
	height: 8px;
	background-color: #d4d7de;
	border-radius: 50%;
}

.trigger-step::after {
	content: '';
	position: absolute;
	left: 3.5px;
	top: 16px;
	width: 1px;
	height: calc(100% - 8px);
	background-color: #bfbfbf;
}

.trigger-configuration-tip {
	display: flex;
	align-items: center;
	font-size: 12px;
	font-weight: 400;
	.tip-icon {
		color: #f56c6c;
		margin-right: 5px;
	}
	.tip-content {
		color: #f56c6c;
	}
}

.trigger-configuration-edit {
	position: relative;
	&-rule,
	&-inform {
		&-title {
			height: 22px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-weight: 500;
		}
	}
	&-rule {
		padding-bottom: 24px;
		&-tip {
			height: 20px;
			font-size: 12px;
			color: #8c8c8c;
		}
	}
	&-inform {
		&-content {
			&-header {
				display: flex;
				height: 32px;
				align-items: center;
				justify-content: space-between;
				margin-top: 8px;
				&-template {
					color: $color-primary;
					cursor: pointer;
				}
			}
			&-content {
				::v-deep .el-select {
					width: 100%;
				}
			}
		}
	}
}
</style>
